#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2022/5/12 18:00
@File: list.py
"""
import re

from qturboframe.lib.utils.check import CheckBasic
from qturboframe.lib.webdriver import SeleniumError
from qturboframe.public_ui.base_element import BaseElement

from BladeFerm.Lib.Common import logger
from BladeFerm.hui12_common.function import get_params


class List(BaseElement, CheckBasic):
    def __init__(self, element_para, father=None, timeout=3):
        try:
            super().__init__(element_para, father, timeout)
            self.list_type = self._element
        except Exception as e:
            logger.error(f'{element_para} 查找页面元素失败。返回异常信息是： {e}')
            self._element = None
            self.list_type = self._element
        finally:
            self.res_elements = None

    def foud_target(self, idname=None):
        by, value, assist = get_params(idname)
        self.res_elements = self.list_type.find_elements_by_attribute(by, value, assist)
        logger.info(f'foud_target result: {self.res_elements}')
        if self.res_elements:
            return self.res_elements
        else:
            raise SeleniumError(f'元素定位表达式 {by, value, assist} 查找后结果为空，请检查')

    def click_target(self, text):
        '''
        点击目标元素，选中操作
        :param text:
        :return:
        '''
        for unit in self.res_elements:
            logger.info(f'found text : {unit.text}')
            if re.search(text, unit.text, re.I):
                unit.click()
                logger.info(f'点击 {text} 元素')
                return True
        else:
            logger.warning(f'no found ele : {text}')
            raise SeleniumError(f'未找到 {text} ！')

    def click(self, text=None, idname=None):
        if idname:
            element_by, element_value, assist = get_params(idname)
        elif not idname and text:
            element_by, element_value, assist = 'xpath', f'.//*[contains(text(),"{text}")]', ''
        else:
            raise SeleniumError(f'text 和 idname 都为空，无法定位！')
        ele = self.list_type.find_element_by_attribute(element_by, element_value, assist)
        ele.click()
        logger.info(f'点击 {ele.text} 元素！')

    def select_target(self, text):
        '''
        勾选多个目标值
        :param text: 'a,v,c'  // 英文的逗号分割
        :return: 选中的文本值列表
        '''
        res = []
        text_list = text.split(',')
        for unit in self.res_elements:
            logger.info(f'found text : {unit.text}')
            if unit.text in text_list:
                unit.click()
                res.append(unit.text)
                logger.info(f'select text : {unit.text}')
        return res
